package simulation1;

import java.util.Date;


public class Road {

	public static final double block = 50.0;
	static final int AVAIL = 0;
	private static final int NOT_AVAIL = 1;
	private static final int RIGHT = 1;
	private static final int LEFT = 0;    
	
	int[][] position;
	//Date dt = new Date();
	
	private Object initial_block_avail;
//	private Object right_avail;
//	private Object left_avail; 
	private Object block_avail;
    int  no_of_segments; 
	
	public Road(int no_of_segments){
		this.no_of_segments=no_of_segments;
		position = new int[2][no_of_segments];
		
		initial_block_avail = new Object();
		//right_avail = new Object();
		//left_avail = new Object();
		block_avail=new Object();
	}

	public void request_initialPosition(Car car, int id, int lane, int segment) {
		
		synchronized(initial_block_avail){
			System.out.println("Car "+id+" has requested for ["+lane+","+segment+"] at "+(new Date().getTime())/100);
			while(!isInitialPositionAvailable(car,id,lane,segment)){
				try { initial_block_avail.wait();}
				catch (InterruptedException e) {e.printStackTrace();}
			}
		}
		
	}

	private synchronized boolean isInitialPositionAvailable(Car car, int id, int lane, int segment) {

		if ( position [lane][segment] == AVAIL){
			position[lane][segment] = NOT_AVAIL;
			System.out.println("		Car "+id+" is in ["+car.lane+","+car.segment+"] at "+(new Date().getTime())/100);
			return true;
		}
		else
			return false;
	}

	

	public void request_Availability(Car car, int id, int lane, int segment) {
		
		synchronized(block_avail){
			
			System.out.println("Car "+id+" has requested for lane! at "+(new Date().getTime())/100);
			
			while(!isPositionAvailable(car,id,lane,segment)){
				try {block_avail.wait();}
				catch (InterruptedException e) {e.printStackTrace();}
			}
			
			synchronized(block_avail){
				block_avail.notifyAll();
			}
			synchronized(initial_block_avail){
				initial_block_avail.notifyAll();
			}
			
		}		
	}

	private synchronized boolean isPositionAvailable(Car car, int id, int lane, int segment) { 
		
		
		if(position[RIGHT][segment+1] == AVAIL){
			position[RIGHT][segment+1] = NOT_AVAIL; //make right block NA
			position[lane][segment] = AVAIL;		//make current block A
			car.lane = RIGHT;						//make car lane as right
			car.segment = car.segment + 1;			//increase cars segment by 1
			//car.goLeft = "NO";						// No need to go left
			System.out.println("		Car "+id+" is in ["+car.lane+","+car.segment+"] at "+(new Date().getTime())/100);
			return true;
		}
			
		else if(position[LEFT][segment+1] == AVAIL){
			position[LEFT][segment+1] = NOT_AVAIL;
			position[lane][segment] = AVAIL;
			car.lane = LEFT;
			car.segment = car.segment + 1;
			System.out.println("		Car "+id+" is in ["+car.lane+","+car.segment+"] at "+(new Date().getTime())/100);	
			return true;
		}		
		else
		{
			return false;
		}
	} 
	
}
